import pandas as pd
import xml.etree.ElementTree as ET
import configparser
import os


def load_config(path="config.ini"):
    config = configparser.ConfigParser()
    config.read(path, encoding="utf-8")
    return config


def parse_strings_xml(xml_path):
    """解析 Android strings.xml 返回 {key: value} 字典"""
    tree = ET.parse(xml_path)
    root = tree.getroot()

    result = {}
    for child in root:
        if child.tag == "string" and "name" in child.attrib:
            key = child.attrib["name"]
            # 获取文本并去掉换行和多余空格
            text = (child.text or "").strip().replace("\n", " ")
            result[key] = text
    return result


def xmls_to_excel(config):
    langs = [lang.strip() for lang in config["lang"]["lang"].split(",")]
    output_file = config["output"]["file"]

    # 读取所有语言的 strings.xml
    lang_data = {}
    for lang in langs:
        xml_path = config["path"][lang]
        if not os.path.exists(xml_path):
            print(f"⚠️ {lang} 文件不存在: {xml_path}")
            continue
        lang_data[lang] = parse_strings_xml(xml_path)
        print(f"✅ 已读取 {lang}: {len(lang_data[lang])} 条记录")

    # 合并所有 key
    all_keys = sorted(set().union(*[data.keys() for data in lang_data.values()]))

    # 生成 DataFrame
    data = {"key": all_keys}
    for lang in langs:
        data[lang] = [lang_data.get(lang, {}).get(k, "") for k in all_keys]

    df = pd.DataFrame(data)

    # 输出 Excel
    df.to_excel(output_file, index=False)
    print(f"🎉 转换完成，Excel 已生成：{output_file}")


if __name__ == "__main__":
    config = load_config("config.ini")
    xmls_to_excel(config)
